import axios from "axios";
import qs from "qs";
import { useUserStore } from "@/store/index";

import router from "@/router/router";
const store = useUserStore();
// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = "/api"; //测试
//axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
//post请求头
// axios.defaults.headers["Token"] = store.Token || "";

//允许跨域携带cookie信息
//axios.defaults.withCredentials = true;
//设置超时
axios.defaults.timeout = 15000;

// 请求拦截
axios.interceptors.request.use(
  (config) => {
    config.headers["Token"] = store.Token || "";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    if (response.data.code == 4) {
      store.$patch({
        userInfo: "",
      });
      router.push("/index/login");
    }

    return Promise.resolve(response.data);
  },
  (error) => {
    console.log(error);
    // alert(JSON.stringify(error), "请求异常", {
    //   confirmButtonText: "确定",
    //   callback: (action) => {
    //     console.log(action);咯破、、
    //   },
    // });
  }
);
export default {
  /**
   * @param {String} url
   * @param {Object} data
   * @returns Promise
   */
  post(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        data: qs.parse(data),
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  get(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url,
        params: data,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
};
